package com.simple.space.modules.shiro.controller;

import com.simple.space.common.constant.Result;
import com.simple.space.modules.shiro.mapper.UserMapper;
import com.simple.space.util.BcryptUtil;
import com.simple.space.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;

/**
 * @ClassName LoginController
 * @Author SimpleTree
 **/
@RestController
public class LoginController {
    private final UserMapper userMapper;

    @Autowired
    public LoginController(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @PostMapping("/login")
    public Result login(@RequestParam("username") String username,
                           @RequestParam("password") String password) {
        String realPassword = userMapper.getPassword(username);
        boolean a = BcryptUtil.match(password, realPassword);
        if (realPassword == null) {
            return new Result(400,"用户名错误");
        } else if (!a) {
            return new Result(400,"密码错误");
        } else {
            return new Result(200, JwtUtil.createJWT(null,"simple",null));
        }
    }

    @RequestMapping(path = "/unauthorized/{message}")
    public Result unauthorized(@PathVariable String message) throws UnsupportedEncodingException {
        return new Result(403,message);
    }
}
